package v1

import (
	"RoccBlog/global"
	"RoccBlog/model"
	v1 "RoccBlog/repository/v1"
	"RoccBlog/service"
	"errors"
	"github.com/gin-gonic/gin"
)

type RoleService struct {
	service.BaseService
	Repository v1.RoleRepository
}

func init() {
	global.RegisterService(&RoleService{
		Repository: v1.RoleRepository{},
	})
}

func (s *RoleService) Add(ctx *gin.Context, data model.Role) error {
	return s.Repository.Create(data)
}

func (s *RoleService) Remove(ctx *gin.Context, id int) error {
	return s.Repository.Delete(id)
}

// ModifyPermission 修改角色权限
func (s *RoleService) ModifyPermission(ctx *gin.Context, data model.Role) error {

	//需要将之前存在的权限都删除
	oldRole, err := s.FindById(ctx, data.Id)
	if err != nil {
		return err
	}
	permissions := oldRole.Permissions
	policies := dataToStringSlice(oldRole.Code, permissions)
	global.CaSbin.RemovePolicies(policies)

	// 更新当前权限
	if len(data.Permissions) > 0 {
		policies = dataToStringSlice(oldRole.Code, data.Permissions)
		global.CaSbin.AddPolicies(policies)
	}
	global.CaSbin.SavePolicy()

	return s.Repository.UpdatePermission(data)
}

// ModifyRouter 修改角色路由
func (s *RoleService) ModifyRouter(data model.Role) error {
	return s.Repository.UpdateRouter(data)
}

func (s *RoleService) Modify(ctx *gin.Context, data model.Role) error {
	return s.Repository.Update(data)
}

func (s *RoleService) FindById(ctx *gin.Context, id int) (model.Role, error) {
	return s.Repository.SelectById(id)
}

func (s *RoleService) Find(ctx *gin.Context) (any, error) {
	size, num := s.GetPage(ctx)
	return s.Repository.Select(num, size)
}

// FindByIdInfo 查询角色id信息
func (s *RoleService) FindByIdInfo(ctx *gin.Context, id int) (*model.Role, error) {

	//可以忽略请求域中不存在用户这个，因为这个权限不会分给white 白名单
	user, _ := s.GetLoginUser(ctx)
	flag := false

	//查找是否存在这个角色
	for _, role := range user.Roles {
		//用户有这个角色的id
		if role.Id == id {
			flag = true
			break
		}
	}

	if !flag {
		//没有这个角色的信息
		return nil, errors.New("用户不存在该角色信息")
	}

	//查询角色信息
	byId, err := s.FindById(ctx, id)
	byId.Permissions = byId.Permissions[0:0]
	return &byId, err
}

func dataToStringSlice(role string, data []model.Permission) [][]string {
	policies := make([][]string, len(data))

	for i, val := range data {
		policies[i] = make([]string, 3)
		policies[i][0] = role
		policies[i][1] = val.URI
		policies[i][2] = val.Method
	}
	return policies
}
